package com.liu.sms.Listener;

import com.liu.shop.common.constant.RabbitConstant;
import com.liu.shop.common.vo.SmsVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SendSms {
    @Value("${sms.host}")
    private String host;

    @Value("${sms.path}")
    private String path;

    @Value("${sms.method}")
    private String method;

    @Value("${sms.appcode}")
    private String appcode;


    // 想要监听的队列
    @RabbitListener(queues = RabbitConstant.SMS_QUEUE)
    public void send(SmsVo smsVo, Channel channel, Message message){

        log.debug("SmsVo:{}",smsVo);

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", smsVo.getPhone());
        querys.put("templateId",smsVo.getTempId());
        querys.put("value",smsVo.getCode());
//        Map<String, String> bodys = new HashMap<String, String>();
        try {
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
            //获取response的body
//            System.out.println(EntityUtils.toString(response.getEntity()));
            // 开启手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("MQ ACK 异常", e);
        } catch (Exception e) {
            log.error("发送短信失败", e);
        }
    }

}
